package cn.rui.service.impl;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.rui.common.Result;
import cn.rui.mapper.UserMapper;
import cn.rui.mapper.UserPermissionMapper;
import cn.rui.pojo.User;
import cn.rui.pojo.UserPermission;
import cn.rui.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 徽州大都督
 * @date 2021/05/13
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPermissionMapper userPermissionMapper;

    @Override
    public Result login(User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", user.getUsername ());
        wrapper.eq ("password", SaBase64Util.encode(user.getPassword ()));
        User user1 = userMapper.selectOne (wrapper);

        if (user1 != null) {
            if (user.getChecked () != null && user.getChecked ()) {
                StpUtil.setLoginId (user1.getUuid (),
                        true   // 设置登录账号id为uuid，第二个参数指定是否为[记住我]，当此值为false后，关闭浏览器后再次打开需要重新登录
                );
            } else {
                StpUtil.setLoginId (user1.getUuid (),
                        false   // 设置登录账号id为uuid，第二个参数指定是否为[记住我]，当此值为false后，关闭浏览器后再次打开需要重新登录
                );
            }

            //设置token值
            user1.setToken (StpUtil.getTokenValue ());
            userMapper.updateById (user1);

            return Result.getSuccess ("登录成功!", user1.getUsername ());
        } else {
            return Result.getFailure ("登录失败!用户名或密码错误!");
        }

        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
//        if("zhang".equals(username) && "123456".equals(password)) {
//            StpUtil.setLoginId(10001);
//            return "index";
//        }
    }

    @Override
    public Result findAll() {

        List<User> userList = userMapper.selectList (null);
        for (User user : userList) {

            //是否封禁
            boolean disable = StpUtil.isDisable (user.getUuid ());
            if (disable) {
                user.setState (1);
            } else {
                user.setState (0);
            }

            Object idByToken = StpUtil.getLoginIdByToken (user.getToken ());
            // 获取当前会话的token信息参数
            //StpUtil.getTokenInfo();

            if (idByToken == null) {
                user.setIsLogin (0);
            } else {
                user.setIsLogin (1);
            }

        }

        return Result.getSuccess ("请求成功", userList);
    }

    @Override
    public Result logoutByLoginId(String uuid) {
        StpUtil.logoutByLoginId (uuid);
        return Result.getSuccess ("操作成功");
    }

    @Override
    public Result disable(String uuid, Integer statu) {

        //Map map = new HashMap();
        //map.put ("uuid",uuid);
        // 封禁指定账号
        // 参数一：账号id
        // 参数二：封禁时长，单位：秒  (86400秒=1天，此值为-1时，代表永久封禁)
        if (statu == 0) {
            //踢下线
            StpUtil.logoutByLoginId (uuid);
            //封禁
            StpUtil.disable (uuid, 86400);
        } else {
            //解除封禁
            StpUtil.untieDisable (uuid);
        }

        return Result.getSuccess ("操作成功");
    }

    @Override
    public User findUserNameByUUid(String uuid) {

        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("uuid", uuid);
        User user = userMapper.selectOne (wrapper);
        return user;
    }

    @Override
    public void updateToken(String uuid) {
        userMapper.updateToken (uuid);
    }

    @Override
    public Result updatePass(String oldPass, String checkPass, String loginName) {
        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username", loginName);
        wrapper.eq ("password", SaBase64Util.encode(oldPass));
        User user = userMapper.selectOne (wrapper);
        if (user==null){
            return Result.getFailure ("旧密码输入错误!");
        }
        user.setPassword (SaBase64Util.encode(checkPass));
        userMapper.updateById (user);
        return Result.getSuccess ("修改密码成功!");
    }

    @Override
    public Result add(String addName, List<Integer> permissionIds) {

        QueryWrapper<User> wrapper = new QueryWrapper<> ();
        wrapper.eq ("username",addName);
        User user = userMapper.selectOne (wrapper);
        if (user!=null){
            return Result.getFailure ("添加失败,用户名已存在!");
        }

        User user1 = new User ();
        //默认密码123456
        user1.setPassword (SaBase64Util.encode("123456"));
        user1.setUsername (addName);
        user1.setRelName ("普通管理员");
        //唯一ID: b17f24ff026d40949c85a24f4f375d42
        String uuid = IdUtil.simpleUUID ();
        user1.setUuid (uuid);
        userMapper.insert (user1);

        //添加权限
        for (Integer permissionId : permissionIds) {
            UserPermission userPermission = new UserPermission ();
            userPermission.setUserUuid (uuid);
            userPermission.setPermissionId (permissionId);
            userPermissionMapper.insert (userPermission);
        }

        return Result.getSuccess ("添加成功!");
    }


}
